package com.base.hong.utils;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.widget.TextView;

import com.base.hong.R;


/***
 * @author kdp
 * @date 2019/7/8 9:45
 * @description
 */
public class CountDownView<V extends TextView> extends CountDownTimer {
    private V view;
    private CountTimeListener countTimeListener;
    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public CountDownView(V view, long millisInFuture, long countDownInterval) {
        //由于消息在排队中也消耗时间，所有加500毫秒来抵消排队的时间
        super(millisInFuture + 500, countDownInterval);
        this.view = view;
        this.view.setClickable(true);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onTick(long millisUntilFinished) {
        if (this.view.isClickable()){
            this.view.setClickable(false);
            if (this.countTimeListener != null)
               this.countTimeListener.onStart();
        }
        this.view.setText(String.format(this.view.getResources().getString(R.string.countdown_time),millisUntilFinished / 1000));
    }


    @Override
    public void onFinish() {
        this.view.setClickable(true);
        if (this.countTimeListener != null){
            this.countTimeListener.onFinish();
        }
    }

    public void setCountTimeListener(CountTimeListener countTimeListener) {
        this.countTimeListener = countTimeListener;
    }

    public interface CountTimeListener {
        /**
         * 计时开始
         */
        void onStart();

        /**
         * 计时结束
         */
        void onFinish();
    }
}



